import React, { useEffect, useState } from 'react';
import {
  Table, Modal, Form, Input, Col, message, Switch, Select, Tabs, Button,
} from 'antd';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import RenderButtom from '@/components/RenderButton';
import SearchBox from '@/components/SearchBox'
import {
  changeRecommend,
  changePopular,
  getProvider,
  fetchGoods,
} from '@/services/goodCenter/invoicing';
import { connect } from 'dva';
import { formItemLayout } from '@/utils/utils';

const hasSearchBtn = JSON.parse(localStorage.getItem('hasSearchBtn'))
const { Option } = Select
const { TabPane } = Tabs

const goodsList = props => {
  const { getFieldDecorator } = props.form;
  const { global } = props;
  const { menus } = global;
  const [data, setColData] = useState([]);
  const [record, setRecord] = useState([]);
  const [record2, setRecord2] = useState([]);
  const [deletea, setdeletea] = useState(false);
  const [deletes, setdeletes] = useState(false);
  const [witha, setwitha] = useState(false);
  const [withs, setwiths] = useState(false);
  const [staffList, setStaffList] = useState([]);
  const [listQuery, setListQuery] = useState({
    isAdmin: 1,
    listStatus: [1],
    pageSize: 10,
    pageNo: 1,
  });
  const getCurrentBtn = menu => {
    const path = props.location.pathname
    return menu.map(i => i.path == path ? i.button : getCurrentBtn(i.children || []))
      .filter(i => i && i.length != 0)
      .reduce((acc, val) => acc.concat(val), []) || [];
  }
  const [info, setInfo] = useState({});
  // 分配\新增角色模态框
  const [isShow, setState] = useState(false);
  const [confirmLoading, setconfirmLoading] = useState(false);

  // 列表
  const getList = async params => {
    const r = await fetchGoods(params);
    console.log(r)
    if (r && r.data) {
      setColData(r.data)
    }
  };
  useEffect(() => {
    let arr = getCurrentBtn(menus)
    arr.forEach(v => {
      if (v.type === 4 && v.name === '移除') {
        setdeletea(true)
      }
      if (v.type === 10001 && v.name === '加入') {
        setwitha(true)
      }
      if (v.type === 95 && v.name === '批量移除') {
        setdeletes(true)
      }
      if (v.type === 93 && v.name === '批量加入') {
        setwiths(true)
      }
    })
  }, [menus])
  useEffect(() => {
    getList(listQuery);
  }, []);

  // 查询
  const searchOneBtn = async params => {
    getList(params);
  };
  const switchRecommend = (id, status) => {
    changeRecommend({ id, status }).then(res => {
      if (res.code === '0') {
        message.success(res.msg)
        getList(listQuery)
      }
    })
  }
  const switchRecommend2 = (id, status) => {
    changePopular({ id, status }).then(res => {
      if (res.code === '0') {
        message.success(res.msg)
        getList(listQuery)
      }
    })
  }
  const columns = [
    {
      title: '序号',
      dataIndex: 'index',
      align: 'center',
      key: 'index',
    },
    {
      title: '商品名称',
      align: 'center',
      key: 'goodsName',
      render: p => {
        if (p.imageUrl) {
          return (
            <div className="tableImg">
              <img src={p.imageUrl} alt=""/>
              <div>{p.goodsName}</div>
            </div>
          )
        }
        return (<span>{p.goodsName}</span>)
      },
    },
    {
      title: '所属门店',
      align: 'center',
      key: 'storeName',
    },
    {
      title: '价格',
      align: 'center',
      key: 'shopPrice',
      render: p => (<span>¥{p.shopPrice}</span>),
    },
    {
      title: '库存',
      align: 'center',
      key: 'goodsStockNum',
    },
    {
      title: '提成模式',
      align: 'center',
      key: 'distributionTypeName',
    },
    {
      title: '佣金',
      align: 'center',
      key: 'money',
    },
    {
      title: '热销推荐',
      align: 'center',
      key: 'topRecommend',
      render: p => (
        <Switch checked={p.topRecommend === 1} onChange={v => switchRecommend(p.goodsRefId, v)} />
      ),
    },
    {
      title: '人气推荐',
      align: 'center',
      key: 'popularityRecommend',
      render: p => (
        <Switch checked={p.popularityRecommend === 1} onChange={v => switchRecommend2(p.goodsRefId, v)} />
      ),
    },
  ];

  const removeRole = async record => {
    handleSupplier({
      id: record.id,
    }, 'DELETE').then(res => {
      if (res.data.code === '0') {
        const index = data.findIndex(e => e.id === record.id);
        setColData(() => {
          data.splice(index, 1);
          return [...data];
        });
      }
    })
  };
  // 新增/修改 模态框
  const handleStatus = record => {
    setState(!isShow);
    if (record) {
      setInfo(record)
    }
  };
  // 查询表单
  const getFields = () => (
    <Col span={18}>
      <Col span={8}>
        <Form.Item label="商品名称">
          <Input onChange={v => { setListQuery({ ...listQuery, goodsName: v.target.value }) }} placeholder="供应商名称/名称" value={listQuery.goodsName} />
        </Form.Item>
      </Col>
    </Col>
  );
  // 查询表单逻辑
  const handleSearch = e => {
    e.preventDefault()
    searchOneBtn(listQuery);
  };

  // 表单提交
  const handleSubmit = e => {
    e.preventDefault();
    props.form.validateFieldsAndScroll((err, values) => {
      console.log(values)
      if (!err) {
        let med = 'POST'
        if (values.id) {
          med = 'PUT'
        }
        setconfirmLoading(true)
        handleSupplier({ storeBusiness: values }, med).then(() => {
          getList(listQuery)
          setState(!isShow);
          setconfirmLoading(false)
        }).catch(() => {
          setconfirmLoading(false)
        })
      }
    });
  };
  // 清空查询条件
  const handleReset = () => {
    const aobj = {
      pageNo: 1,
      pageSize: 10,
    }
    setListQuery(aobj)
    getList(aobj)
  };
  // 按钮逻辑
  const handleBtn = type => {
    if (type === 10001 || type === 93) {
      if (record.length !== 1) return message.warning('请勾选一条数据！');
      if (type === 10001) {
        console.log(93)
      }
      if (type === 93) {
        console.log(93)
      }
    } else {
      if (record2.length !== 1) return message.warning('请勾选一条数据！');
      if (type === 4) {
        console.log(4)
      }
      if (type === 95) {
        console.log(95)
      }
    }
  };
  const rowSelection = {
    type: 'radio',
    onChange: (selectedRowKeys, selectedRows) => {
      setRecord(selectedRows)
    },
  };
  const rowSelection2 = {
    type: 'radio',
    onChange: (selectedRowKeys, selectedRows) => {
      setRecord2(selectedRows)
    },
  };
  return (
    <PageHeaderWrapper>
      {/* 查询条件 */}
      <SearchBox handleReset={handleReset} handleSearch={handleSearch} getFields={getFields} />
      <Tabs defaultActiveKey="1" onChange={v => {
        let aq = listQuery
        aq.pick = v === '2'
        setListQuery({ ...listQuery, pick: v === '2' })
        getList(aq)
      }}>
        <TabPane tab="未加入" key="1">
          { witha ? (<Button type="primary" onClick={() => handleBtn(10001)}>加入</Button>) : '' }
          { withs ? (<Button type="primary" style={{margin: '0 10px'}} onClick={() => handleBtn(93)}>批量加入</Button>) : '' }
          <Table className="marginT10" columns={columns} dataSource={hasSearchBtn ? data : []} rowSelection={rowSelection} rowKey={rec => rec.id} />
        </TabPane>
        <TabPane tab="已加入" key="2">
          { deletea ? (<Button type="danger" onClick={() => handleBtn(4)}>移除</Button>) : '' }
          { deletes ? (<Button type="danger" style={{margin: '0 10px'}} onClick={() => handleBtn(95)}>批量移除</Button>) : '' }
          <Table className="marginT10" columns={columns} dataSource={hasSearchBtn ? data : []} rowSelection={rowSelection2} rowKey={rec => rec.id} />
        </TabPane>
      </Tabs>
      {/* 新增/修改 */}
      <Modal
        title="新增/修改"
        visible={isShow}
        confirmLoading={confirmLoading}
        onOk={handleSubmit.bind(this)}
        onCancel={handleStatus.bind(this)}
        destroyOnClose
      >
        <Form {...formItemLayout}>
          <Form.Item label="供应商名称">
            {getFieldDecorator('name', {
              initialValue: info.name,
              rules: [
                {
                  required: true,
                  message: '请输入供应商名称',
                },
              ],
            })(<Input placeholder="请输入供应商名称" />)}
          </Form.Item>
          <Form.Item label="联系人">
            {getFieldDecorator('contact', {
              initialValue: info.contact,
              rules: [
                {
                  required: true,
                  message: '请输入联系人',
                },
              ],
            })(<Input placeholder="请输入联系人" />)}
          </Form.Item>
          <Form.Item label="联系电话">
            {getFieldDecorator('phoneNumber', {
              initialValue: info.phoneNumber,
              rules: [
                {
                  required: true,
                  message: '请输入联系电话',
                },
              ],
            })(<Input placeholder="请输入联系电话" />)}
          </Form.Item>
          <Form.Item label="联系地址">
            {getFieldDecorator('address', {
              initialValue: info.address,
              rules: [
                {
                  required: true,
                  message: '请输入联系地址',
                },
              ],
            })(<Input placeholder="请输入联系地址" />)}
          </Form.Item>
          <Form.Item label="备注">
            {getFieldDecorator('remarks', {
              initialValue: info.remarks,
            })(<Input placeholder="请输入备注" />)}
          </Form.Item>
        </Form>
      </Modal>
    </PageHeaderWrapper>
  );
};
export default connect(({ role, global }) => ({
  role,
  global,
  hasSearchBtn: global.hasSearchBtn,
}))(Form.create()(goodsList));
